package com.shanzmoo.core.domain.pay;

import com.shanzmoo.core.pay.sdk.wxpay.WXPayConstants;
import com.shanzmoo.core.pay.sdk.wxpay.WXPayUtil;
import io.swagger.annotations.ApiModel;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信网页支付数据
 * @author Gzhao 2021/1/3
 */
@Data
@ApiModel("微信网页支付数据")
public class WxWapPayResp implements Serializable {
    private static final long serialVersionUID = 1758L;

    /**
     * 公众号名称，由商户传入
     */
    private String appId;

    /**
     * 时间戳，自1970年以来的秒数
     */
    private String timeStamp;

    /**
     * 随机串
     */
    private String nonceStr;

    /**
     * 订单详情扩展字符串
     */
    private String packageStr;

    /**
     * 微信签名方式
     */
    private String signType;

    /**
     * 微信签名
     */
    private String paySign;

    public static WxWapPayResp createByMap(Map<String,String> respMap, String key) throws Exception {
        if (!WXPayConstants.SUCCESS.equals(respMap.get("result_code"))) {
            return null;
        }


        WxWapPayResp wxWapPayResp = new WxWapPayResp();
        wxWapPayResp.setAppId(respMap.get("appid"));
        wxWapPayResp.setTimeStamp(String.valueOf(WXPayUtil.getCurrentTimestamp()));
        wxWapPayResp.setNonceStr(respMap.get("nonce_str"));
        wxWapPayResp.setPackageStr("prepay_id=" + respMap.get("prepay_id"));
        wxWapPayResp.setSignType(WXPayConstants.HMACSHA256);

        //二次签名
        Map<String,String> ternMap=new HashMap<>();
        ternMap.put("appId", wxWapPayResp.getAppId());
        ternMap.put("timeStamp", wxWapPayResp.getTimeStamp());
        ternMap.put("nonceStr", wxWapPayResp.getNonceStr());
        ternMap.put("package", wxWapPayResp.getPackageStr());
        ternMap.put("signType", wxWapPayResp.getSignType());


        String paySign = WXPayUtil.generateSignature(ternMap, key, WXPayConstants.SignType.HMACSHA256);

        wxWapPayResp.setPaySign(paySign);

        return wxWapPayResp;
    }
}
